using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using Comteck.Dto.Sys;
using Comteck.Ktt.Properties;
using Comteck.Ktt.Services.Sys;
using Comteck.Winforms;
using Comteck.Winforms.Infrastructure;
using Comteck.Winforms.Utils;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using Microsoft.Extensions.DependencyInjection;

namespace Comteck.Ktt.Base {
  /// <summary>
  /// 
  /// </summary>
  public partial class FrmMain : FrmSkinBase {

    #region fields

    /// <summary>
    /// 上一次按下的按钮
    /// </summary>
    private MenuAuthDto prevMenu = null;

    /// <summary>
    /// 上一次按下的按钮
    /// </summary>
    private int prevMenuIndex = -1;

    /// <summary>
    /// 权限文本描述内容
    /// </summary>
    private string userInfoFormat = string.Empty;

    /// <summary>
    /// 权限文本描述内容
    /// </summary>
    private string orgInfoFormat = string.Empty;

    /// <summary>
    /// 鼠标移动上去的颜色
    /// </summary>
    private Color hoverColore = Color.FromArgb(64, 102, 199);

    /// <summary>
    /// 鼠标移动上去的颜色
    /// </summary>
    private Color userPanelHoverCore = Color.FromArgb(245, 245, 245);

    // 客户端拖拽调整界面的大小
    const int HTLEFT = 10;
    const int HTRIGHT = 11;
    const int HTTOP = 12;
    const int HTTOPLEFT = 13;
    const int HTTOPRIGHT = 14;
    const int HTBOTTOM = 15;
    const int HTBOTTOMLEFT = 0x10;
    const int HTBOTTOMRIGHT = 17;

    private readonly IMenuAuthService _menuAuthService;

    #endregion

    #region ctor

    public FrmMain(IMenuAuthService _menuAuthService) {
      this._menuAuthService = _menuAuthService;
      InitializeComponent();

      // 权限文本描述内容
      userInfoFormat = (barLoginUser.SuperTip.Items[1] as ToolTipItem)?.Text;

      // 添加最大化和还原事件
      this.SetMinMaxCloseEvents(
        imgMin, Resources.minimize_hover_3x, Resources.minimize_3x,
        imgMax, Resources.maximize_3x, Resources.reduction_3x,
        imgClose, Resources.close_hover_3x, Resources.close_3x,
        new List<Control> { panelTopLeft, panelTopCenter, lblCompanyText},
        () => this.ClosePopupContainer()
      );
    }

    #endregion

    #region methods

    #region 初始化菜单

    /// <summary>
    /// 初始化菜单
    /// </summary>
    private async Task InitMenu() {
      SysGlobal.MenuList.DataSource = (await _menuAuthService.GetActiveDtosAsync()).ToList();
    }

    #endregion


    #region 打开窗口
    /// <summary>
    /// 打开窗口
    /// </summary>
    /// <param name="menu">菜单信息</param>
    /// <param name="isReOpenWhenExists">是否重新打开窗体(当已存在时)</param>
    public override void OpenForm(MenuAuthDto menu, bool isReOpenWhenExists = false, int? showMode = null, params object[] args) {
      // 路径不存在
      if (menu == null || string.IsNullOrWhiteSpace(menu.Form_Path) || string.IsNullOrWhiteSpace(menu.Form_Assembly_Name)) {
        return;
      }
      // 加载程序集
      var assembly = SysGlobal.LoadedAssemblys.FirstOrDefault(x => x.GetName().Name == menu.Form_Assembly_Name);

      if (assembly == null) {
        try {
          assembly = Assembly.Load(menu.Form_Assembly_Name);
          SysGlobal.LoadAssemblys();
        } catch (Exception ex) {
          Logger.Error("加载程序集 {0} 失败".FormatWith(menu.Form_Assembly_Name), ex);
        }
      }

      if (assembly == null) {
        this.ShowMsg("该菜单所在的程序集不存在");
        return;
      }

      // 从程序集创建对象
      var type = assembly.GetType(menu.Form_Path);
      if (type == null) {
        this.ShowMsg($"表单 {menu.Form_Path} 不存在");
        return;
      }

      // 如果该窗口已经存在,则直接选中该窗口
      var tmp = this.MdiChildren.FirstOrDefault(x => x.GetType() == type);
      if (tmp != null) {
        // 是否重新打开窗体(当已存在时)
        if (isReOpenWhenExists) {
          xtraTabbedMdiManager1.Pages[tmp].MdiChild.Close();
        } else {
          xtraTabbedMdiManager1.SelectedPage = xtraTabbedMdiManager1.Pages[tmp];
          return;
        }
      }

      try {
        // 待创建的表单
        //if (Utils.AssemblyHelper.CreateInstance(type, args) is Form form) {
        if (SysGlobal.ServiceProvider.GetRequiredService(type) is Form form) {
            // 附加信息(传递窗体参数)
          form.Tag = menu;

          // 打开窗口
          showMode = showMode ?? menu.Show_Mode;

          if (showMode == (int) EnumMenuShowMode.Dialog) {
            form.ShowDialog();
          } else {
            this.AsyncOpenMdiForm(form);
          }
        }
      } catch (Exception ex) {
        this.ShowMsg("打开窗口【{0}】失败".FormatWith(menu.Name));
        Logger.Error("打开窗口【{0}】失败".FormatWith(menu.Name), ex);
      }
    }

    /// <summary>
    /// 异步打开首页
    /// </summary>
    private void OpenHomeForm() {
      // 有主页了
      if (this.MdiChildren.Any(x => x is FrmDashboard)) {
        return;
      }

      this.AsyncOpenMdiForm(new FrmDashboard());
    }

    /// <summary>
    /// 异步打开窗口
    /// </summary>
    /// <param name="form"></param>
    private void AsyncOpenMdiForm(Form form) {
      // 判断最多允许打开的界面数
      var mis_TabPage_Count = 8;

      if (xtraTabbedMdiManager1.Pages.Count >= mis_TabPage_Count) {
        DevHelper.ShowMsg($"系统最多支持同时打开 {mis_TabPage_Count} 个界面！");
        return;
      }

      void action() {
        form.MdiParent = this;
        form.Show();
      };

      this.InvokeMethodSync(action);
    }

    #endregion

    #region 查找定位菜单

    /// <summary>
    /// 
    /// </summary>
    /// <param name="treeMenu"></param>
    /// <param name="buttonEdit"></param>
    private void FindMenu(TreeList treeMenu, ButtonEdit buttonEdit) {
      var keyword = buttonEdit.EditValue.ToString(true).TrimSafe();

      if (string.IsNullOrWhiteSpace(keyword)) {
        return;
      }

      // 数据源
      if (!(treeMenu.DataSource is IList<MenuAuthDto> list)) {
        return;
      }

      // 查找第一个匹配的菜单
      for (var i = prevMenuIndex + 1; i < list.Count(); i++) {
        prevMenuIndex = i;

        if (this.IsMenuAuthSameByKeyword(list[i], keyword, false)) {
          prevMenu = list[i];
          break;
        } else {
          prevMenu = null;
        }
      }

      // 如果没有找到,则不作处理
      if (prevMenu == null) {

        if (prevMenuIndex == list.Count() - 1) {
          var msg = "您已经搜索到菜单的末尾,是否需要重新查询？"
            + Environment.NewLine
            + "点\"是\"重头搜索"
            + Environment.NewLine
            + "点\"否\"取消搜索";
          var dialog = XtraMessageBox.Show(msg, "提示", MessageBoxButtons.YesNo,
            MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

          this.prevMenuIndex = -1;

          if (dialog == System.Windows.Forms.DialogResult.Yes) {
            this.FindMenu(treeMenu, buttonEdit);
          } else {
            treeMenu.Focus();
          }

        }
        return;
      }

      // 根据主键查找节点
      var node = treeMenu.FindNodeByKeyID(prevMenu.Id);

      // 节点不存在
      if (node == null) {
        return;
      }

      // 向上递归展开菜单
      this.LoopExpandNode_Up(node.ParentNode);

      // 设置焦点
      treeMenu.SetFocusedNode(node);
      treeMenu.FocusedNode = node;
    }

    /// <summary>
    /// 当前菜单是否符合查找的条件
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="keyword"></param>
    /// <returns></returns>
    private bool IsMenuAuthSameByKeyword(MenuAuthDto dto, string keyword, bool retry) {
      // 查找变量
      var id = dto.Id; // 菜单id
      var name = (dto.Name ?? string.Empty).ToLower(); //菜单名称
      //var namePy = ChineseHelper.ConvertToFirstLetter(name).ToLower();
      //var formNamePy = ChineseHelper.ConvertToFirstLetter(formName).ToLower();
      var formPath = (dto.Form_Path ?? string.Empty).ToLower(); // 表单路径
      var keywordLower = (keyword ?? string.Empty).ToLower();

      // 判断菜单id、表单id、菜单名、表单名、表单路径
      var flag = string.Equals(id, keyword)
        || name.Contains(keywordLower)
        || formPath.Contains(keywordLower);

      return flag;
    }

    /// <summary>
    /// 向上递归展开菜单
    /// </summary>
    /// <param name="parentNode">父节点</param>
    private void LoopExpandNode_Up(TreeListNode parentNode) {
      // 父节点不存在
      if (parentNode == null) {
        return;
      }

      // 展开当前节点
      parentNode.Expanded = true;

      // 再向上查找
      this.LoopExpandNode_Up(parentNode.ParentNode);
    }

    #endregion

    #region 添加拖动事件

    /// <summary>
    /// 
    /// </summary>
    private void AddHeadDragEventAll() {
      var list = new List<Control>() {
        this,
        panelTop,panelTopLeft,panelTopCenter,panelTopRight,
        lblCompanyText,
      };
      list.AddDragEvents();
    }

    #endregion

    #region 设置底部信息

    /// <summary>
    /// 设置底部信息
    /// </summary>
    private void SetFooterInfo() {
      // 版本信息
      barVersion.Caption = $"版本：{SysGlobal.Settings.Version}";
      barDevelopMode.Caption = "运行模式";

      // 用户信息
      barLoginUser.Caption = $"{SysGlobal.LoginUser.Name}({SysGlobal.LoginUser.Id})";
      (barLoginUser.SuperTip.Items[1] as ToolTipItem).Text = string.Format(userInfoFormat, SysGlobal.LoginUser.Id, SysGlobal.LoginUser.Name);
      barLoginUser.Visibility = BarItemVisibility.Always;

      // 时间
      DevHelper.SetFullControlTimeMove(barCurDateTime);
    }

    #endregion

    #region 皮肤设置

    /// <summary>
    /// 皮肤设置
    /// </summary>
    private void SetDevSkinBar() {
      SkinHelper.InitSkinGallery(galleryControl1, true, false);
      galleryControl1.Gallery.AllowFilter = false;
      galleryControl1.Gallery.ItemClick += (sender, e) => {

        var setDic = new Dictionary<string, string>();
        setDic.Add(nameof(SysGlobal.Settings.Dev_SkinName), e.Item.Caption);

        try {
          ConfigManagerHelper.SaveUserConfig(setDic);
          SysGlobal.LoadAppSettings();
        } catch (Exception ex) {
          Logger.Error("dev样式设置失败", ex);
        }
      };
    }

    #endregion

    #region 打开和关闭popupcontainer

    /// <summary>
    /// 
    /// </summary>
    /// <param name="edit"></param>
    private void OpenPopupContainer(IEnumerable<PopupContainerEdit> editList) {
      editList.Each(edit => {
        this.OpenPopupContainer(edit);
      });
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="edit"></param>
    private void OpenPopupContainer(PopupContainerEdit edit) {
      if (edit.IsPopupOpen == false) {
        edit.ShowPopup();
      }
    }

    /// <summary>
    /// 关闭全部的展示界面
    /// </summary>
    private void ClosePopupContainer() {
      //this.ClosePopupContainer(new[] { imgUser, imgWeather, imgDownload, imgNotice });
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="edit"></param>
    private void ClosePopupContainer(IEnumerable<PopupContainerEdit> editList) {
      editList.Each(edit => {
        this.ClosePopupContainer(edit);
      });
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="edit"></param>
    private void ClosePopupContainer(PopupContainerEdit edit) {
      if (edit.IsPopupOpen) {
        edit.ClosePopup();
      }
    }

    #endregion

    #region 设置菜单图片

    ///// <summary>
    ///// 设置菜单图片
    ///// </summary>
    //private void SetMenuImages() {
    //  // 16 * 16的图片：功能菜单
    //  var images = this.imageCollection1 = SysGlobal.GetMenuImageCollection(new Size(16, 16));
    //  this.ckMainTree.SelectImageList = null;
    //  this.ckMainTree.StateImageList = images;

    //  // 32 * 32的图片：收藏夹
    //  var images32 = this.imageList1 = SysGlobal.GetMenuImageList(new Size(32, 32));
    //  this.lvCustomMenu.LargeImageList = images32;

    //  // 采用大图标方式
    //  this.lvCustomMenu.View = View.LargeIcon;
    //}

    #endregion

    #endregion

    #region form load

    private async void FrmMain_Load(object sender, EventArgs e) {
      // 设计模式
      if (this.DesignMode) {
        return;
      }

      // bind event
      this.ckMainTree.CustomDrawNodeCell += new DevExpress.XtraTreeList.CustomDrawNodeCellEventHandler(this.ckMainTree_CustomDrawNodeCell);
      this.ckMainTree.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.ckMainTree_MouseDoubleClick);
      this.ckMainTree.GetStateImage += new DevExpress.XtraTreeList.GetStateImageEventHandler(this.ckMainTree_GetStateImage);
      this.xtraTabbedMdiManager1.PageAdded += new DevExpress.XtraTabbedMdi.MdiTabPageEventHandler(this.xtraTabbedMdiManager1_PageAdded);
      this.xtraTabbedMdiManager1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.xtraTabbedMdiManager1_MouseDown);
      this.btnCloseTabCurrent.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnCloseTabCurrent_ItemClick);
      this.btnCloseTabRight.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnCloseTabRight_ItemClick);
      this.btnCloseTabLeft.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnCloseTabLeft_ItemClick);
      this.btnCloseTabOther.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnCloseTabOther_ItemClick);
      this.btnCloseTabAll.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnCloseTabAll_ItemClick);


      this.BtnRefreshMenu.MouseClick += new System.Windows.Forms.MouseEventHandler(this.BtnRefreshMenu_MouseClick);
      this.btnExpandLeftTree.MouseClick += new System.Windows.Forms.MouseEventHandler(this.btnExpandLeftTree_MouseClick);
      this.btnCollapeLeftMenu.MouseClick += new System.Windows.Forms.MouseEventHandler(this.btnCollapeLeftMenu_MouseClick);
      this.ckMenuFilter.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ckMenuFilter_KeyDown);
      this.ckMenuFilter.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.ckMenuFilter_ButtonClick);
      this.ckMenuFilter.Click += new System.EventHandler(this.ckMenuFilter_Click);
      this.ckMenuFilter.EditValueChanged += new System.EventHandler(this.ckMenuFilter_EditValueChanged);
      this.ckMainTree.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ckMainTree_MouseUp);


      this.SetStyle(ControlStyles.UserPaint, true);
      this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
      this.SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲 

      // 激活窗口
      this.Activate();

      // 设置底部信息
      this.SetFooterInfo();

      // 添加拖动事件
      this.AddHeadDragEventAll();

      // 设置菜单图标
      //this.SetMenuImages();

      // 绑定左侧菜单，选中菜单的背景色：浅蓝色
      ckMainTree.Appearance.FocusedCell.BackColor = Color.FromArgb(211, 205, 250);
      BindHelper.BindMainMenu(ckMainTree, SysGlobal.MenuList);
      await this.InitMenu();

      // 设置皮肤
      this.SetDevSkinBar();

      // 最大化
      this.WindowState = FormWindowState.Maximized;

      // 打开首页
      this.OpenHomeForm();
    }

    #endregion

    #region MainTree Menu Event

    /// <summary>
    /// 菜单树绘画节点
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMainTree_CustomDrawNodeCell(object sender, CustomDrawNodeCellEventArgs e) {
      // 无节点
      if (e == null || e.Node == null) {
        return;
      }

      var tree = sender as TreeList;

      // 选中的节点
      var model = tree.GetDataRecordByNode(e.Node) as MenuAuthDto;

      // no data
      if (model == null) {
        return;
      }

      e.CellText = model.Name;
    }

    /// <summary>
    /// 打开
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMainTree_MouseDoubleClick(object sender, MouseEventArgs e) {
      // 非鼠标左键
      if (e.Button != System.Windows.Forms.MouseButtons.Left) {
        return;
      }

      var tree = sender as TreeList;

      // 选中的节点
      var node = tree.FocusedNode;
      if (node == null) {
        return;
      }

      // 节点绑定的对象
      var menu = tree.GetDataRecordByNode(node) as MenuAuthDto;

      if (menu == null) {
        return;
      }

      // 打开窗口
      this.OpenForm(menu);
    }

    /// <summary>
    /// 设置菜单的状态图片
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMainTree_GetStateImage(object sender, GetStateImageEventArgs e) {
      //// 选中的节点
      //var model = this.ckMainTree.GetDataRecordByNode(e.Node) as MenuAuthDto;

      //// 菜单或者图片不存在
      //if (model == null || model.Icon.IsNullOrEmpty()) {
      //  // 直接设置成第1张的默认图片
      //  e.NodeImageIndex = 0;
      //  //return;
      //} else {
      //  // 设置图片
      //  e.NodeImageIndex = this.imageCollection1.Images.Keys.IndexOf(model.Icon);
      //}
    }

    #endregion

    #region Mid Page

    /// <summary>
    /// TAB窗口最后一个鼠标时间
    /// </summary>
    private DateTime m_LastClick = System.DateTime.Now;

    /// <summary>
    /// 添加页
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void xtraTabbedMdiManager1_PageAdded(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e) {
      // 当前打开的窗体
      var form = e.Page.MdiChild;
      if (form == null) {
        return;
      }

      // 窗口的图片
      var icon = string.Empty;

      // 首页特殊处理
      if (form is FrmDashboard) {
        e.Page.ShowCloseButton = DefaultBoolean.False;
        e.Page.Pinned = true;
        e.Page.AllowPin = false;
      } else {
        e.Page.ShowCloseButton = DefaultBoolean.True;
      }

      // ImageCollection.GetImageListImage
      e.Page.ImageIndex = 0;
    }

    /// <summary>
    /// 鼠标按下
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void xtraTabbedMdiManager1_MouseDown(object sender, MouseEventArgs e) {
      // 根据鼠标类型分别处理
      switch (e.Button) {
        case System.Windows.Forms.MouseButtons.Left:
          // 鼠标左键

          // 点击
          var dt = DateTime.Now;

          // 间隔时间
          var span = dt.Subtract(m_LastClick);

          // 点击小于300毫秒，则认为是双击
          if (span.TotalMilliseconds < 300) {
            // 窗口有效
            if (this.xtraTabbedMdiManager1.SelectedPage != null
              && this.xtraTabbedMdiManager1.SelectedPage.ShowCloseButton != DefaultBoolean.False) {
              // close
              this.xtraTabbedMdiManager1.SelectedPage.MdiChild.Close();
            }

            // 这里取消双击状态
            m_LastClick = dt.AddMinutes(-1);
          } else {
            this.m_LastClick = dt;
          }

          break;
        case System.Windows.Forms.MouseButtons.Right:
          // 鼠标右键

          // 计算鼠标右键的位置
          var hint = xtraTabbedMdiManager1.CalcHitInfo(e.Location);

          // 点击无效，或者么有点在TabPage上,则不处理
          if (hint.IsValid == false || hint.Page == null) {
            return;
          }

          // 打开的窗口
          var form = this.xtraTabbedMdiManager1.SelectedPage.MdiChild;

          // not exists
          if (form == null) {
            return;
          }

          // 鼠标位置
          var p = form.PointToScreen(e.Location);

          // 计算误差
          p = new Point(p.X, p.Y - 20);

          this.tabPopupMenu.ShowPopup(this.barManager1, p);
          break;
        default:
          break;
      }

    }

    #endregion

    #region Mid Page Mouse Event

    /// <summary>
    /// 关闭当前
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCloseTabCurrent_ItemClick(object sender, ItemClickEventArgs e) {
      this.xtraTabbedMdiManager1.CloseCurrent();
    }

    /// <summary>
    /// 关闭右侧
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCloseTabRight_ItemClick(object sender, ItemClickEventArgs e) {
      this.xtraTabbedMdiManager1.CloseRight();
    }

    /// <summary>
    /// 关闭左侧
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCloseTabLeft_ItemClick(object sender, ItemClickEventArgs e) {
      this.xtraTabbedMdiManager1.CloseLeft();
    }

    /// <summary>
    /// 关闭其他
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCloseTabOther_ItemClick(object sender, ItemClickEventArgs e) {
      this.xtraTabbedMdiManager1.CloseOther();
    }

    /// <summary>
    /// 关闭全部
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCloseTabAll_ItemClick(object sender, ItemClickEventArgs e) {
      this.xtraTabbedMdiManager1.CloseAll();
    }

    #endregion

    #region 菜单树相关操作

    /// <summary>
    /// 刷新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void BtnRefreshMenu_MouseClick(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        await this.InitMenu();
      }
    }

    /// <summary>
    /// 功能树展开
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnExpandLeftTree_MouseClick(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        ckMainTree.ExpandAll();
      }
    }


    /// <summary>
    /// 功能树合并
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCollapeLeftMenu_MouseClick(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        ckMainTree.CollapseAll();
      }
    }

    /// <summary>
    /// 回车快速定位
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMenuFilter_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyCode == Keys.Enter) {
        FindMenu(ckMainTree, ckMenuFilter);
      }
    }

    /// <summary>
    /// 查找定位
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMenuFilter_ButtonClick(object sender, ButtonPressedEventArgs e) {
      if (e.Button.Tag.To<int>() == 1) {
        FindMenu(ckMainTree, ckMenuFilter);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMenuFilter_Click(object sender, EventArgs e) {
      ckMenuFilter.SelectAll();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMenuFilter_EditValueChanged(object sender, EventArgs e) {
      prevMenu = null;
    }

    /// <summary>
    /// 菜单树鼠标右键按下，显示右键菜单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ckMainTree_MouseUp(object sender, MouseEventArgs e) {
      // object
      var tree = sender as TreeList;

      // 
      if (e.Button == MouseButtons.Right && ModifierKeys == Keys.None && tree.State == TreeListState.Regular) {
        // 取得鼠标的位置
        Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
        TreeListHitInfo hitInfo = tree.CalcHitInfo(e.Location);

        // 如果是单元格,则定位
        if (hitInfo.HitInfoType == HitInfoType.Cell) {
          tree.SetFocusedNode(hitInfo.Node);
        }

        // 弹出右键
        if (tree.FocusedNode != null) {
          this.popupMainTree.ShowPopup(p);
        }
      }
    }

    #endregion

    #region 关闭

    /// <summary>
    /// 校验当前是否在做日结
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
      if (this.ShowConfirmWhenClose == false) {
        return;
      }

      // 提示框
      var result = XtraMessageBox.Show("您确定要退出本系统吗？", "提示",
        MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

      // 不退出系统
      if (result == System.Windows.Forms.DialogResult.Cancel) {
        e.Cancel = true;
        return;
      }
    }

    /// <summary>
    /// 关闭界面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void FrmMain_FormClosed(object sender, FormClosedEventArgs e) {
      this.UseWaitCursor = true;
      Logger.Info("关闭主程序 开始");
      // 释放资源
      SysGlobal.Close();

      Logger.Info("关闭主程序 结束");
      this.UseWaitCursor = false;
    }

    #endregion

    #region 客户端拖拽调整界面的大小

    /// <summary>
    /// 客户端拖拽调整界面的大小
    /// </summary>
    /// <param name="m"></param>
    protected override void WndProc(ref Message m) {
      var borderWidth = 5;
      switch (m.Msg) {
        case 0x0084:
          base.WndProc(ref m);
          var vPoint = new Point((int) m.LParam & 0xFFFF,
              (int) m.LParam >> 16 & 0xFFFF);
          vPoint = PointToClient(vPoint);
          if (vPoint.X <= borderWidth)
            if (vPoint.Y <= borderWidth)
              m.Result = (IntPtr) HTTOPLEFT;
            else if (vPoint.Y >= base.ClientSize.Height - borderWidth)
              m.Result = (IntPtr) HTBOTTOMLEFT;
            else
              m.Result = (IntPtr) HTLEFT;
          else if (vPoint.X >= base.ClientSize.Width - borderWidth)
            if (vPoint.Y <= borderWidth)
              m.Result = (IntPtr) HTTOPRIGHT;
            else if (vPoint.Y >= base.ClientSize.Height - borderWidth)
              m.Result = (IntPtr) HTBOTTOMRIGHT;
            else
              m.Result = (IntPtr) HTRIGHT;
          else if (vPoint.Y <= borderWidth)
            m.Result = (IntPtr) HTTOP;
          else if (vPoint.Y >= base.ClientSize.Height - borderWidth)
            m.Result = (IntPtr) HTBOTTOM;
          break;
        case 0x0201://鼠标左键按下的消息 
          m.Msg = 0x00A1;//更改消息为非客户区按下鼠标 
          m.LParam = IntPtr.Zero;//默认值 
          m.WParam = new IntPtr(2);//鼠标放在标题栏内

          //以下做了一些修正，确保放大缩小按钮区域可以正常使用
          //Point point = Control.MousePosition;
          //point = PointToClient(point);
          //if (point.X < this.Width - 100 && point.Y < 30) {
          //  m.Msg = 0x00A1;//更改消息为非客户区按下鼠标 
          //  m.LParam = IntPtr.Zero;//默认值 
          //  m.WParam = new IntPtr(2);//鼠标放在标题栏内 
          //}

          base.WndProc(ref m);
          break;
        default:
          base.WndProc(ref m);
          break;
      }
    }

    #endregion

  }
}
